package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DepartmentContent;
import com.isunland.managesystem.entity.DeptSearchContent;
import com.isunland.managesystem.entity.EmployeeLoanContent;
import com.isunland.managesystem.entity.EmployeeLoanOriginal;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

public class DepartmentCollectListFragment extends BaseListFragment {

  protected static final String EXTRA_VLAUE =
      "com.isunland.managesystem.ui.DepartmentCollectListFragment.EXTRA_VLAUE";

  private static final int SEARCH_COLLECT = 0;
  private MyProgressDialog mdialog;
  private DepartmentCollectListAdapter mAdapter;
  private ArrayList<EmployeeLoanContent> mList;// 解析列表集合
  private BaseVolleyActivity mActivity;

  //默认当天-30到当天,填报时间
  private String startDate =
      MyDateUtil.dateToString(MyDateUtil.getBeforeOneMonth(), MyDateUtil.TYPE_DATE);
  //填报结束时间
  private String endDate = MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE);
  private int mPage = 1;
  private CurrentUser mUser;

  private DeptSearchContent searchContent;

  private String appDeptCode = "";//部门编码
  private String appDeptName = "";//部门名称

  private String contractId = "";//合同ID
  private String contractProjectId = "";//项目ID
  private String partId = "";//客户ID

  protected String contractName;//合同名称

  protected String customerName = "";//客户名字
  protected String customerId = "";//客户id

  protected String certificateCodes = "";//单据类型编码codes
  protected String certificateNames = "";//单据类型names

  /**
   * 1.如果单据类型的值只选择一个并且值包含 DJLB-CWYS,将查询时间给 beginbudgetDate,endbudgetDate 赋值,
   * 其他的情况给 beginapplyTime,endapplyTime
   * 2.如果按照单据类型查询并且 单据类型值中不包含 CWZC-KXYZSQ 和 CWSR-KXYS ,
   * 参数 queryRelation 为空 否则参数为 1 如果参数 queryRelation 值为 1
   * 那么 queryCertificateCodes 值为 "'"+(memberCode)+"-DJLB-CWZC-WWXMKZC','"+(memberCode)+"-DJLB-CWZC-WLCGKZCYHT','"+(memberCode)+"-DJLB-CWSR-CJXMKSR','"+(memberCode)+"-DJLB-CWSR-WLXSKSRYHT'"
   * 其他情况值为 空
   */

  //	@Override
  //	public void onAttach(Context context) {
  //		//1，先获得登录人所在部门  2，部门编码默认筛选第一个部门
  //		mUser=CurrentUser.newInstance(context);
  //		mActivity=(BaseVolleyActivity) getActivity();
  //		VolleyGetDept();//获得登录人所属部门
  //		super.onAttach(context);
  //	}
  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mListview.setDividerHeight(0);
  }

  @Override public void onCreate(Bundle savedInstanceState) {

    setHasOptionsMenu(true);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle("部门收入支出汇总列表");
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    VolleyGetDept();
    super.onCreate(savedInstanceState);
  }

  private void VolleyGetDept() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_DEPT_LIST);
    HashMap<String, String> params = new HashMap<>();

    params.put("memberCode", mUser.getMemberCode());
    params.put("isPaging", "0");
    params.put("style", "tree");
    params.put("postKindCodes", "'positionType01'");
    params.put("orderField", "porg_code,order_no");
    params.put("orderSeq", "asc");
    params.put("staffCode", mUser.getJobNumber());

    //		showDialog();
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        DepartmentContent[] contents = new Gson().fromJson(arg0, DepartmentContent[].class);
        if (contents == null || contents.length == 0) {
          appDeptCode = "";
          appDeptName = "";
        } else {
          //默认选择第一个部门进行查询
          appDeptCode = contents[0].getOrgCode();
          appDeptName = contents[0].getOrgName();
        }
        volleyPost();
        LogUtil.i("部门arg0=====" + appDeptCode + "," + appDeptName);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show("解析异常！");
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_add_search, menu);
    menu.getItem(0).setVisible(false).setEnabled(false);//隐藏添加按钮
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityIntent(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      //查询（部门名称和code，开始时间，结束时间）
      case R.id.menu_item_querys:
        Intent i = new Intent(getActivity(), SearchDepatrtCollectActivity.class);
        //			i.putExtra(SearchDepatrtCollectFragment.EXTRA_DEPTNAME, appDeptName);
        //			i.putExtra(SearchDepatrtCollectFragment.EXTRA_DEPTCODE, appDeptCode);
        //			i.putExtra(SearchDepatrtCollectFragment.EXTRA_STARTDATE, startDate);
        //			i.putExtra(SearchDepatrtCollectFragment.EXTRA_ENDDATE, endDate);
        DeptSearchContent content =
            new DeptSearchContent(appDeptCode, appDeptName, startDate, endDate, certificateCodes,
                certificateNames, contractId, contractName, customerId, customerName);
        i.putExtra(SearchDepatrtCollectFragment.EXTRA_VLAUE, content);
        startActivityForResult(i, SEARCH_COLLECT);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {
    //		Mode mode=refreshView.getCurrentMode();
    //		if (mode.equals(Mode.PULL_FROM_START)) {
    //			mPage=1;
    //		}
    //		if (mode.equals(Mode.PULL_FROM_END)) {
    //			mPage++;
    //		}
    volleyPost();
    super.onRefresh(refreshView);
  }

  @Override public String getUrl() {

    return ApiConst.ULR_DEPT_COLLECT_LIST;
  }

  @Override public HashMap<String, String> getparameters() {

    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", mUser.getMemberCode());
    params.put("dataStatus", "checkPass");
    params.put("noCode", "NBWLYFPYC-FPYC");
    /**
     * 如果单据类型的值只选择一个并且值包含 DJLB-CWYS,将查询时间给 beginbudgetDate,endbudgetDate 赋值,
     * 其他的情况给 beginapplyTime,endapplyTime
     * 如果按照单据类型查询并且 单据类型值中不包含 CWZC-KXYZSQ 和 CWSR-KXYS ,
     * 参数 queryRelation 为空 否则参数为 1 如果参数 queryRelation 值为 1
     * 那么 queryCertificateCodes 值为 "'"+(memberCode)+"-DJLB-CWZC-WWXMKZC','"+(memberCode)+"-DJLB-CWZC-WLCGKZCYHT','"+(memberCode)+"-DJLB-CWSR-CJXMKSR','"+(memberCode)+"-DJLB-CWSR-WLXSKSRYHT'"
     * 其他情况值为 空
     */

    params.put("codeFlagList", certificateCodes);

    if (!TextUtils.isEmpty(certificateCodes)
        && certificateCodes.indexOf("CWZC-KXYZSQ") < 0
        && certificateCodes.indexOf("CWSR-KXYS") < 0) {
      params.put("queryRelation", "");
      params.put("queryCertificateCodes", "");
    } else {
      params.put("queryRelation", "1");
      params.put("queryCertificateCodes", "'"
          + (mUser.getMemberCode())
          + "-DJLB-CWZC-WWXMKZC','"
          + (mUser.getMemberCode())
          + "-DJLB-CWZC-WLCGKZCYHT','"
          + (mUser.getMemberCode())
          + "-DJLB-CWSR-CJXMKSR','"
          + (mUser.getMemberCode())
          + "-DJLB-CWSR-WLXSKSRYHT'");
    }

    //		填报开始时间，结束时间
    if (!TextUtils.isEmpty(certificateCodes) && (certificateCodes.indexOf(",") < 0) && (
        certificateCodes.indexOf("DJLB-CWYS")
            > 0)) {
      params.put("beginbudgetDate", startDate);
      params.put("endbudgetDate", endDate);
    } else {
      params.put("beginapplyTime", startDate);
      params.put("endapplyTime", endDate);
    }
    params.put("appDeptCode", appDeptCode);
    params.put("contractId", contractId);
    params.put("contractProjectId", "");//项目id
    params.put("partId", customerId);//客户id
    params.put("orderField", "IFNULL(OCCUR_DATE,APPLY_TIME) desc,order_no");
    params.put("orderSeq", "desc");
    params.put("isPaging", "0");
    return params;
  }

  @Override public void resolveResponse(String json) {
    LogUtil.i("汇总 json===" + json);
    EmployeeLoanOriginal original = new Gson().fromJson(json, EmployeeLoanOriginal.class);
    List<EmployeeLoanContent> rows = original.getRows();
    if (mList == null) {
      mList = new ArrayList<>();
    }
    mList.clear();
    mList.addAll(rows);

    LogUtil.i("appDeptCode====" + appDeptCode);

    setAdapter(mList);
  }

  protected void setAdapter(ArrayList<EmployeeLoanContent> mList2) {
    if (mAdapter == null) {
      mAdapter = new DepartmentCollectListAdapter(getActivity(), mList2);
    }
    setListAdapter(mAdapter);
    ((DepartmentCollectListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {

    EmployeeLoanContent mCollectContent = mList.get(position - 1);
    Intent i = new Intent(getActivity(), DetailDepartmentCollectActivity.class);
    i.putExtra(DetailDepartmentCollectFragment.EXTRA_VLAUE, mCollectContent);
    startActivity(i);

    super.onListItemClick(l, v, position, id);
  }

  private void getData(DeptSearchContent content) {
    appDeptCode = content.getAppDeptCode();
    appDeptName = content.getAppDeptName();//部门名称
    startDate = content.getStartDate();//开始时间
    endDate = content.getEndDate();//结束时间

    contractId = content.getContractId();//合同id
    contractName = content.getContractName();//合同名称
    customerName = content.getCustomerName();//客户名字
    customerId = content.getCustomerId();//客户id

    certificateCodes = content.getCertificateCodes();//单据类型编码codes
    certificateNames = content.getCertificateNames();//单据类型names
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    if (requestCode == SEARCH_COLLECT) {
      DeptSearchContent content = (DeptSearchContent) data.getSerializableExtra(EXTRA_VLAUE);
      getData(content);
      volleyPost();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  //开始是否加载和显示空视图
  @Override protected void isPostStart(boolean isPostStart, boolean isShowEmpty) {
    super.isPostStart(false, false);
  }
}
